package org.xgluo.services;

/**
 * 编程式的事务管理
 * 在业务代码中嵌入事务管理器，实现事务管理
 */

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import static java.lang.Thread.sleep;

@Service
public class UserDemoService {

    @Autowired
    TransactionTemplate transactionTemplate;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    PlatformTransactionManager transactionManager;

    Logger logger = LoggerFactory.getLogger("UserDemoService");

    public void updateUserInfo(){

        TransactionStatus transactionStatus = transactionManager.getTransaction(new DefaultTransactionDefinition());
        try {
            jdbcTemplate.update("update infouser set name='123' where iduser='123' ");
            //int i= 2/0;
            //transactionManager.commit(transactionStatus);
            logger.info("事务是否完成："+transactionStatus.isCompleted());
            transactionManager.commit(transactionStatus);
//            sleep(20000);
            logger.info("事务是否完成："+transactionStatus.isCompleted());

        }catch (Exception e ){
            transactionManager.rollback(transactionStatus);
            e.printStackTrace();
        }
    }

    public void updateUserInfo1(){

        try {
            transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                @Override
                protected void doInTransactionWithoutResult(TransactionStatus status) {
                    try {
                        jdbcTemplate.update("update infouser set name='124' where iduser='124' ");
                    }catch (Exception e){
                        LoggerFactory.getLogger("updateUserInfo1").error("方法执行异常");
                        status.setRollbackOnly();
                        e.printStackTrace();
                    }
                }
            });
        }catch (Exception e ){
            e.printStackTrace();
        }

    }

}
